package com.example.composableexample

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

/**
 * author: LiLiang
 * createTime: 2022/9/18-10:10
 * remark:
 **/

@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun TextFieldStateExample() {
    val viewModel = viewModel<SingleUpViewModel>()
    Column {
        OutlinedTextField(
            value = viewModel.username,
            onValueChange = { viewModel.updateUsername(it) }
        )
        val usernameHasError by viewModel.usernameHasError.collectAsState()
        if (usernameHasError) {
            Text(text = "用户名验证错误", color = Color.Red)
        }
    }


}

//处理TextField状态最佳实践
class SingleUpViewModel : ViewModel() {

    var username by mutableStateOf("")
        private set

    @OptIn(ExperimentalCoroutinesApi::class)
    val usernameHasError: StateFlow<Boolean> =
        snapshotFlow { username }
            //  执行验证 username 逻辑
            .mapLatest { false }
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5000),
                initialValue = false
            )

    fun updateUsername(input: String) {
        username = input
    }
}

//  错误演示
class SingleUpViewModelError : ViewModel() {

    // 不建议使用XXXFlow 响应流定义状态变量
    private val _username = MutableStateFlow("")
    val username = _username.asStateFlow()

    /***
     * 错误的示范  异步有可能会出错
     */
    fun updateUsername(input: String) {
        viewModelScope.launch {
            delay(10)
            _username.value = input
        }
    }
}

